package com.cow.net.tcp;



import java.util.concurrent.TimeUnit;

import com.csgyy.Constraint;
import com.csgyy.tcp.domain.DeviceValue;
import com.csgyy.tcp.domain.TypeData;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.HashedWheelTimer;

/**
 * Description:
 * Author:Giousa
 * Date:2017/2/9
 * Email:65489469@qq.com
 */
public class Client {
 /*   private NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
    private Channel channel;
    private Bootstrap bootstrap;



    public void start() {
        try {
            bootstrap = new Bootstrap();
            bootstrap
                    .group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline p = socketChannel.pipeline();
                            p.addLast(new IdleStateHandler(0, 0, 5));
//                            p.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, -4, 0));
                            p.addLast(new MsgPackDecode());
                            p.addLast(new MsgPackEncode());
                            p.addLast(new ClientHandler(Client.this));
                        }
                    });
            doConnect();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/




    ConnectionWatchdog watchdog = null;
    protected final HashedWheelTimer timer = new HashedWheelTimer();

    private Bootstrap boot;

    private final ConnectorIdleStateTrigger idleStateTrigger = new ConnectorIdleStateTrigger();

    public void connect() throws Exception {


        String host = Constraint.tcpserverip;
        int port =Constraint.tcpPort;


        EventLoopGroup group = new NioEventLoopGroup();

        boot = new Bootstrap();
        boot.group(group).channel(NioSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO));

          watchdog = new ConnectionWatchdog(boot, timer, port,host, true) {

            public ChannelHandler[] handlers() {
                return new ChannelHandler[] {
                        this,
                        new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS),
                        idleStateTrigger,
                        new ProtobufVarint32FrameDecoder(),
                new ProtobufDecoder(
                        DeviceValue.Request.getDefaultInstance()),

               new ProtobufVarint32LengthFieldPrepender(),
                new ProtobufEncoder(),
                        new HeartBeatClientHandler()
                };
            }
        };


        boot.option(ChannelOption.SO_KEEPALIVE, true);
        boot.option(ChannelOption.TCP_NODELAY, true);

        final ChannelFuture[] future = new ChannelFuture[1];
        //进行连接
        try {
            synchronized (boot) {
                boot.handler(new ChannelInitializer<Channel>() {

                    //初始化channel
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(watchdog.handlers());
                    }
                });

                realConnect(host, port, future);
            }

            // 以下代码在synchronized同步块外面是安全的
            future[0].sync();
        } catch (Throwable t) {
            throw new Exception("connects to  fails", t);
        }
    }

    private void realConnect(String host, int port, ChannelFuture[] future) {
        future[0] = boot.connect(host,port);

        future[0].addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture futureListener) throws Exception {
                if (futureListener.isSuccess()) {
                    watchdog.channel = futureListener.channel();
                    System.out.println("Connect to server successfully!");
                } else {
                    System.out.println("Failed to connect to server, try connect after 4s");
                    futureListener.channel().eventLoop().schedule(new Runnable() {
                        @Override
                        public void run() {
                            realConnect(host, port, future);
                        }
                    }, 4, TimeUnit.SECONDS);

                }
            }
        });
    }


    /**
     * 发送数据 每隔2秒发送一次
     * @throws Exception
     */
    public void sendData(String data) throws Exception {
            if ( watchdog.channel != null &&  watchdog.channel.isActive()) {



               // System.out.println("client 发送数据:"+deviceValue.toString());


                DeviceValue.Request.Builder deviceValue  =DeviceValue.Request.newBuilder();
                deviceValue.setPackageType(TypeData.DATA); //数据数据类型
                deviceValue.setDataType(TypeData.DATAFDJ); //发动机类型
                deviceValue.setContext(data);
                deviceValue.setCompanyId(Constraint.companyId);


                watchdog.channel.writeAndFlush(deviceValue);
            }



    }



  /*  *//**
     * 重连机制,每隔2s重新连接一次服务器
     *//*
    protected void doConnect() {
        if (channel != null && channel.isActive()) {
            return;
        }

        ChannelFuture future = bootstrap.connect(Constraint.tcpserverip, Constraint.tcpPort);

        future.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture futureListener) throws Exception {
                if (futureListener.isSuccess()) {
                    channel = futureListener.channel();
                    System.out.println("Connect to server successfully!");
                } else {
                    System.out.println("Failed to connect to server, try connect after 2s");

                    futureListener.channel().eventLoop().schedule(new Runnable() {
                        @Override
                        public void run() {
                            doConnect();
                        }
                    }, 2, TimeUnit.SECONDS);
                }
            }
        });
    }*/



}
